package cn.lwj.controller;

import cn.lwj.common.R;
import cn.lwj.common.ServiceException;
import cn.lwj.pojo.*;
import cn.lwj.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jetbrains.annotations.Nls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import sun.security.krb5.internal.PAEncTSEnc;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;


    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public R<String> login(@RequestBody User user, HttpSession session){
        System.out.println("phone === " + user.getPhone());

        //        如果用户不存在则新增用户
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone,user.getPhone());
        User u = userService.getOne(lqw);
        if( u == null){
            u = user;
            u.setStatus(1);
            String idStr = IdWorker.getIdStr();
            u.setName("U_" + idStr);
            userService.save(u);
        }

        session.setAttribute("user",u.getId());

        return R.success("登录成功");
    }

    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){

//        1.消除session的userId

        session.removeAttribute("user");

        return R.success("退出成功");
    }


    /**
     * 分页查询用户
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){

        System.out.println("/////////////");
        System.out.println( page);
        System.out.println( pageSize);

        Page<User> userPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.like( name != null,User::getName,name);
        userLambdaQueryWrapper.orderByAsc(User::getPhone);

        userService.page(userPage,userLambdaQueryWrapper);

        return R.success(userPage);
    }


    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> delete(String id){
        System.out.println(" id === " + id);

        User user = userService.getById(id);

        if(user.getStatus() == 1){
            throw new ServiceException("用户状态启用中，不可以删除");
        }

        boolean res = userService.removeById(user.getId());
        if(res){
//            删除用户也要对应删除用户的地址信息 购物车信息 以及订单信息
//            删除购物车
            LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
            shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,user.getId());
            shoppingCartService.remove(shoppingCartLambdaQueryWrapper);

//            删除对应收货地址
            LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
            addressBookLambdaQueryWrapper.eq(AddressBook::getUserId,user.getId());
            addressBookService.remove(addressBookLambdaQueryWrapper);

//            删除对应订单 以及详情信息
            LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
            ordersLambdaQueryWrapper.eq(Orders::getUserId,user.getId());
            List<Orders> ordersList = ordersService.list(ordersLambdaQueryWrapper);

            boolean removeOrders = ordersService.remove(ordersLambdaQueryWrapper);

            if(removeOrders){
                for (Orders orders : ordersList) {
                    LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,orders.getId());
                    orderDetailService.remove(orderDetailLambdaQueryWrapper);
                }
            }
        }
        return R.success("删除成功");
    }


    /**
     * 更改用户状态
     * @param user
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody User user){
        System.out.println(user.toString());
//        根据用户id修改用户状态
        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(User::getId,user.getId());
        lambdaUpdateWrapper.set(user.getStatus()!=null,User::getStatus,user.getStatus());
        boolean res = userService.update(lambdaUpdateWrapper);
        if(res){
            return R.success("状态修改成功");
        }else{
            return R.error("状态修改失败");
        }
    }


    /**
     * 新增用户
     * @param user
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody User user){

        System.out.println(user.toString());

        user.setStatus(1);

        boolean res = userService.save(user);

        if(res){
            return R.success("新增成功");
        }else{
            return R.error("新增失败");
        }
    }


    /**
     * 根据id获取用户信息
     * @param id
     * @return
     */
    @GetMapping
    public R<User> getById(String id){
        System.out.println("id === " + id);
        User user = userService.getById(id);
        
        return R.success(user);
    }

}
